package com.ruoyi.reim.trajectory;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.activiti.domain.ActWorkflowFormData;
import com.ruoyi.activiti.domain.dto.WorkflowTrajectory;
import com.ruoyi.activiti.domain.vo.FlowVo;
import com.ruoyi.activiti.service.impl.ProcessFlowsService;
import com.ruoyi.activiti.service.impl.WorkflowTrajectoryService;
import com.ruoyi.common.core.activiti.MyActivitiInterface;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.reim.domain.WorkflowReim;
import com.ruoyi.reim.service.WorkflowReimService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

/**
 * <p>报销审批实现类</p>
 * <p>创建日期：2021-07-19</p>
 *
 * @author zhou-qf
 */
@Component
public class ReimActivitiImpl implements MyActivitiInterface {

    private final static String key  = "reimApprove";

    @Autowired
    private WorkflowTrajectoryService workflowTrajectoryService;

    @Autowired
    private WorkflowReimService workflowReimService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ProcessFlowsService processFlowsService;

    /**
     * 通过候选用户获取人员姓名
     * @param key
     * @param processId
     * @return
     */
    @Override
    public List<SysUser> queryNameByUsers(String key, String processId) {
        WorkflowReim workflowReim = getWorkflowReim(processId);

        if(workflowReim == null){
            return null;
        }

        SysUser sysUser = sysUserService.selectUserByUserName(workflowReim.getCreateBy());
        // 一个审批流可能有多个候选用户，所以需要通过业务判断是当前哪个审批级别的候选用户
        // 财务部长审批
        if(key.contains("deptLeader")){
            return sysUserService.selectApprovalInfo("cwbz", sysUser.getDeptId());
        }
        return null;
    }

    /**
     * 通过候选组获取人员姓名
     * @param key
     * @param processId
     * @return
     */
    @Override
    public List<SysUser> queryNameByGroups(String key, String processId) {
        return sysUserService.selectApprovalInfo(key, null);
    }

    /**
     * 保存轨迹信息
     * @param param
     * @return
     */
    @Override
    public int saveTrajectory(Object param) {
        List<ActWorkflowFormData> acwfds = (List<ActWorkflowFormData>)param;

        // 获取业务ID
        String tId = acwfds.get(0).getBusinessKey();
        // 获取详情信息
        WorkflowReim workflowReim = workflowReimService.selectWorkflowReimById(tId);

        // 先更新轨迹表中当前审批的轨迹信息，然后判断是否有下个审批节点，如果有，把下个审批节点的轨迹添加到表中
        WorkflowTrajectory queryParam = new WorkflowTrajectory();
        queryParam.settId(tId);
        queryParam.setApprovalStatus("待审批");
        List<WorkflowTrajectory> list = workflowTrajectoryService.selectWorkflowTrajectoryList(queryParam);
        String createBy = SecurityUtils.getUsername();

        if(!list.isEmpty()){
            final WorkflowTrajectory workflowTrajectory = list.get(0);
            workflowTrajectory.setApprovalStatus("已审批");

            workflowTrajectory.setApprovalId(createBy);
            acwfds.stream().forEach(item ->{
                if("审批意见".equals(item.getControlName())){
                    workflowTrajectory.setApprovalResult(item.getControlValue());
                }
                if("批注".equals(item.getControlName())){
                    workflowTrajectory.setApprovalContent(item.getControlValue());
                }
            });
            workflowTrajectory.setCompleteTime(new Date());
            // 修改原轨迹信息
            workflowTrajectoryService.updateWorkflowTrajectory(workflowTrajectory);
        }

        List<String> stringList = processFlowsService.nextNode(workflowReim.getInstanceId());

        if(!stringList.isEmpty()){
            WorkflowTrajectory workflowTrajectory = new WorkflowTrajectory();
            workflowTrajectory.settId(tId);
            workflowTrajectory.setBillCode(workflowReim.getBillCode());
            workflowTrajectory.setType(key);
            workflowTrajectory.setInstanceId(workflowReim.getInstanceId());
            workflowTrajectory.setApprovalStatus("待审批");

            List<FlowVo> flowVoList = processFlowsService.queryFlowList(workflowReim.getInstanceId());
            for(FlowVo flowVo : flowVoList){
                if(flowVo.getTaskName().equals(stringList.get(0))){
                    workflowTrajectory.setApprovalNodeName(flowVo.getTaskName());
                    List<SysUser> userList = null;
                    if(StringUtils.isNotEmpty(flowVo.getTaskUsers())){
                        userList = this.queryNameByUsers(flowVo.getTaskUsers(), workflowReim.getInstanceId());
                    } else if(StringUtils.isNotEmpty(flowVo.getTaskGroups())){
                        userList = this.queryNameByGroups(flowVo.getTaskGroups(), workflowReim.getInstanceId());
                    }
                    String names = "";
                    String emails = "";
                    for(int i = 0, len = userList.size(); i < len; i++){
                        names += userList.get(i).getNickName();
                        emails += userList.get(i).getEmail();

                        if(i < (len - 1)){
                            names += ",";
                            emails += ",";
                        }
                    }
                    workflowTrajectory.setApprovalName(names);
                    workflowTrajectory.setApprovalEmail(emails);
                }
            }
            Date date = new Date();
            workflowTrajectory.setStartTime(date);
            workflowTrajectory.setCreateBy(createBy);
            workflowTrajectory.setCreateTime(date);
            return workflowTrajectoryService.insertWorkflowTrajectory(workflowTrajectory);
        }else{
            //没有下一个审批节点了，说明审批流程全部结束
            //首先获取到审批结果：同意/不同意
            AtomicReference<String> approvalResult = new AtomicReference<>("");
            acwfds.stream().forEach(item ->{
                if("审批意见".equals(item.getControlName())){
                    approvalResult.set(item.getControlValue());
                }
            });
            String result = approvalResult.get();
            if("同意".equals(result)){
                String paramRe = "billcode="+workflowReim.getBillCode();
                // post调用远程接口,这个pathUrl是临时写的请求路径，因为网报系统那边接口还没写好，到时候一替换就行了
                String pathUrl = "http://192.168.1.229:9081/isolation/person/check/add";
                HttpUtils.sendPost(pathUrl,paramRe);
            }
        }
        return 0;
    }

    /**
     * 报销审批关键字
     * @param processKey
     * @return
     */
    @Override
    public boolean support(String processKey) {
        return key.equals(processKey);
    }

    /**
     * 通过实例ID获取报销基本信息
     * @param instanceId
     * @return
     */
    private WorkflowReim getWorkflowReim(String instanceId){
        WorkflowReim workflowReim = new WorkflowReim();
        workflowReim.setInstanceId(instanceId);
        List<WorkflowReim> list = workflowReimService.selectWorkflowReimList(workflowReim);
        if(list.isEmpty()){
            return null;
        }
        return list.get(0);
    }
}
